package com.medical.blood.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpJscode2SessionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.medical.blood.entity.User;
import com.medical.blood.mapper.UserMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

@Service
public class UserLoginService {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserMapper userMapper;

    private static final String SECRET_KEY = "your_secret_key"; // 请更换为安全的密钥
    private static final long EXPIRATION_TIME = 604800000; // 7天，单位毫秒

    public String login(String code) throws WxErrorException {
        // 1. 通过微信授权接口获取openid
        WxMpJscode2SessionResult session = wxMpService.getUserService().getSessionInfo(code);
        String openid = session.getOpenid();

        // 2. 检查用户是否已存在
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid));
        if (user == null) {
            // 如果不存在，创建新用户，初始状态设为启用（1）
            user = new User();
            user.setOpenid(openid);
            user.setStatus(1);
            userMapper.insert(user);
        }

        // 3. 生成JWT令牌
        String token = Jwts.builder()
                .setSubject(user.getId().toString())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();

        return token;
    }
}